/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.grnt.buddy;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.grnt.buddy.BuddiesTreeControler.BuddiesCtlException;
import org.grnt.common.CommonFunc;
import org.grnt.dbcommon.ControlBean;
import static org.grnt.dbcommon.DataControler.TransOpt;

/**
 *
 * It is subclass of ControlBean, and it implements change user's password action.
 * @author Sayid
 */
public class ChangPassword implements ControlBean {
	final Long   userId;
	final String password;
	final String sqlStr = "UPDATE gt_users SET password = '?' WHERE user_id = '?'";

	/**
	 * Constructure with two parameter, one is userId another is password.
	 * @param userId User id.
	 * @param password New password for correct user.
	 */
	public ChangPassword(Long userId, String password) {
		this.password = password;
		this.userId = userId;
	}

	final public List<String> getCommands() {
		List<String> result = new ArrayList<String>();
		String command = CommonFunc.sqlStrFormat(sqlStr, password, userId.toString());
		command = CommonFunc.sqlNullStr2NullVal(command);
		result.add(command);
		return result;
	}

	final public boolean doInTransaction() {
		try {
			BuddiesTreeControler.chPassword(userId, password, false);
			return true;
		} catch (BuddiesCtlException ex) {
			Logger.getLogger(ChangPassword.class.getName()).log(Level.SEVERE, null, ex);
			ex.printStackTrace();
			return false;
		}
	}

	public void doAfterTransaction(TransOpt opt) {
		try {
			if (opt == TransOpt.ROLLBACK){
				BuddiesTreeControler.userRollbackCh(userId);
			} else {
				BuddiesTreeControler.userCommitCh(userId);
			}
		} catch (BuddiesCtlException ex) {
			ex.printStackTrace();
			Logger.getLogger(ChangPassword.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
}
